package com.westos.denglu.sevlet;

import org.apache.commons.lang3.RandomUtils;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class YanzhengmaServlet extends HttpServlet {
    private static final int WIDTH = 100;
    private static final int HEIGHT = 40;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();

        //制作一张验证码图片，格式为jpg
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        //设置背景色
        g.setColor(Color.WHITE);
        //填充背景色
        g.fillRect(0,0,WIDTH,HEIGHT);
        //设置前景色
        g.setColor(Color.RED);
        //设置字体
        Font font=new Font("仿宋",Font.BOLD,20);
        g.setFont(font);
        //获取4位随机字母
        String randomString = getRandomString(4);
        session.setAttribute("ranstr",randomString);
        g.drawString(randomString,20,30);
        //设置干扰线
        for(int i=0;i<20;i++){
            int x1 = RandomUtils.nextInt(0,WIDTH);
            int x2 = RandomUtils.nextInt(0,WIDTH);
            int y1 = RandomUtils.nextInt(0,HEIGHT);
            int y2 = RandomUtils.nextInt(0,HEIGHT);
            Color color = new Color(RandomUtils.nextInt(0,255),RandomUtils.nextInt(0,255),RandomUtils.nextInt(0,255));
            g.setColor(color);
            g.drawLine(x1,x2,y1,y2);
        }

        ImageIO.write(image,"jpg",response.getOutputStream());
        //response.getWriter().print("success");
    }
    //获取len个随机字母
    private String getRandomString(int len){
        String result = "";
        for(int i=0;i<len;i++){
            char c = (char) RandomUtils.nextInt(65, 91);
            result = result+c;
        }

        return result;
    }
}
